﻿using StableDiffusionTools.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StableDiffusionTools.Controls
{
    public class TrackBarEx : TrackBar
    {
        public bool AllowRollover { get; set; } = false;

        protected override void OnMouseWheel(MouseEventArgs e)
        {
            ((HandledMouseEventArgs)e).Handled = true;
            int amount = ModifierKeys.HasFlag(Keys.Control) ? SmallChange : LargeChange;
            int deltaTimes = Math.Abs(e.Delta) / 120;
            int newValue = Value + ((e.Delta > 0) ? amount * deltaTimes : -amount * deltaTimes);
            if (AllowRollover)
            {
                if (newValue > Maximum)
                {
                    Value = Minimum;
                }
                else if (newValue < Minimum)
                {
                    Value = Maximum;
                }
                else
                {
                    Value = newValue;
                }
            }
            else
            {
                Value = MathUtil.Clamp(newValue, Minimum, Maximum);
            }

            base.OnMouseWheel(e);
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.PageUp:
                case Keys.PageDown:
                case Keys.Down:
                case Keys.Up:
                    e.Handled = true;
                    int newValue = Value + ((e.KeyCode == Keys.PageUp || e.KeyCode == Keys.Up) ? LargeChange : -LargeChange);
                    if (AllowRollover)
                    {
                        if (newValue > Maximum)
                        {
                            Value = Minimum;
                        }
                        else if (newValue < Minimum)
                        {
                            Value = Maximum;
                        }
                        else
                        {
                            Value = newValue;
                        }
                    }
                    else
                    {
                        Value = MathUtil.Clamp(newValue, Minimum, Maximum);
                    }
                    break;
                default:
                    break;
            }

            base.OnKeyDown(e);
        }
    }
}
